<template>
	<view class="box" :class="['qn-page-' + theme]">
		<view class="close-view"><text class="ibonfont ibonguanbi1" @click="closePage"></text></view>
		<view class="top-bg"></view>
		<view class="welcome-title">
			<view>您好，欢迎</view>
			<view>登录喵开单平台</view>
		</view>
		<view class="logo-img">
			<image :src="baseSet.images" mode="aspectFill"></image>
		</view>
		<view class="login-bg">
			<view class="login-container">
				<image class="login-image" :src="imgHost + '/statics/login-img.jpg'" mode="aspectFill"></image>
				<view class="login-btn-view">
					<button class="wx-Btn primary-bg" open-type="getPhoneNumber" @getphonenumber="getphonenumber">
						<text class="btn-text">快速授权登录</text>
					</button>
				</view>
				<!-- 短信登录功能暂时注释
				<view class="wx-change-btn" @click="login_type = 2">
					<text class="ibonfont ibonshouji1 wxicon" style="transform: translateY(-4rpx);display: inline-block;"></text>
					短信验证登录
				</view>
				-->
			</view>
			<!-- 短信登录功能暂时注释
			<block v-if="login_type === 2">
				<view class="tab-ul">
					<view class="tab-li" @click="login_type = 1">手机号快捷登录</view>
					<view class="tab-on">手机验证登录</view>
				</view>
				<view class="input-ul">
					<view class="input-li">
						<text class="ibonfont ibonshouji1"></text>
						<input type="number" placeholder-class="input-pl" v-model="phoneNumber" placeholder="请输入手机号" />
					</view>
					<view class="input-li">
						<text class="ibonfont ibonyanzhengma"></text>
						<input type="number" placeholder-class="input-pl" v-model="smsCode" placeholder="请输入验证码" />
						<view class="yzm-view">
							<text v-if="is_dis_yzm">{{ num }}s后重新发送</text>
							<text v-else @click="getYzm()">获取验证码</text>
						</view>
					</view>
				</view>
				<view class="login-btn primary-bg" @click="appletsBindMobile()">登录</view>
			</block>
			-->
			<view class="bottom-xieyi">
				<checkbox-group bindchange="checkboxChange" @change="handleChange" v-model="treaty">
					<checkbox value="1" />阅读并同意以下条款
				</checkbox-group>
				<label>
					<view @click="yhxyPage()">《用户服务协议》</view>
					<view>及</view>
					<view @click="ysxyPage()">《隐私保护政策》</view>
				</label>
			</view>
		</view>
	</view>
</template>

<script>
import webUrl from '@/config.js';
export default {
	data() {
		return {
			imgHost : webUrl.QN_URL,
			loginCode: '',
			is_dis_yzm: false,
			num: 60,
			source: 5,
			smsCode: '',
			phoneNumber: '',
			login_type: 1,
			xyvalue: 0,
		};
	},
	computed: {
		baseSet() {
			return this.$store.state.baseSet;
		},
		source() {
			return this.$common.source();
		},
		staffId() {
			return this.$store.state.staffId;
		},
		businessmanId() {
			return this.$store.state.businessmanId;
		}
	},
	onShow() {
		// #ifdef MP
		uni.hideHomeButton();
		// #endif
	},
	onLoad() { },
	methods: {
		closePage() { // 拒绝跳转主页面
			this.goPage('/pages/index/index', 'switchTab');
		},
		yhxyPage() { // 拒绝跳转主页面
			this.goPage('/pagesT/binding/yhxy');
		},
		ysxyPage() { // 拒绝跳转主页面
			this.goPage('/pagesT/binding/ysxy');
		},
		handleChange(e) {
			this.xyvalue = e.detail.value;
		},
		async getLoginCode() {
			return new Promise((resolve, reject) => {
				uni.login({
					provider: 'weixin',
					success: async res => {
						this.loginCode = res.code;
						console.log(this.loginCode, 'code');
						await this.Login(this.loginCode);
						resolve(this.loginCode);
					}
				});
			});
		},
		async getphonenumber(e) { // 静默模式获取openid 和 unionid
			if (this.xyvalue == 0) {
				this.$api.msg('请先勾选同意协议');
				return false;
			}
			if (e.detail.errMsg != 'getPhoneNumber:ok') {
				this.$api.msg(e.detail.errMsg);
				return false;
			}
			await this.getLoginCode();

			const iv = e.detail.iv;
			const encryptedData = e.detail.encryptedData;
			this.$u.api
				.decryptData({
					openid: this.$common.getOpenid(),
					iv: iv,
					encryptedData: encryptedData
				})
				.then(async (data) => {
					console.log(data, 'data123456');
					this.phoneNumber = data.data.phoneNumber;
					uni.setStorageSync('phoneNumber', this.phoneNumber);
					// #ifdef MP-WEIXIN
					this.appletsBindMobile('wx');
					// #endif
					// #ifdef MP-TOUTIAO
					this.appletsBindMobile('byteDance');
					// #endif
				});
		},
		async Login(code) { // 微信小程序通过code获取openId
			uni.showLoading();
			await this.$u.api
				.getOpenId({
					code: code
				})
				.then(data => {
					uni.hideLoading();
					// code 用过之后 清除缓存的code
					this.loginCode = '';
					console.log(data, 'Login');
					if (!data.data.unionid) {
						uni.setStorageSync('openid', data.data.openid);
					} else {
						uni.setStorageSync('openid', data.data.openid);
						uni.setStorageSync('unionid', data.data.unionid);
						//this.checkBindMiniProgram(data.data.openid, data.data.unionid);
					}
				});
		},
		/*decryptData(iv, encryptedData, openid) { // 反解 unionId
			console.log('1111');
			this.$u.api
				.decryptData({
					openid: openid,
					iv: iv,
					encryptedData: encryptedData
				})
				.then(data => {
					console.log(data);
					uni.setStorageSync('openid', openid);
					uni.setStorageSync('unionid', data.data.unionId);
					//this.checkBindMiniProgram(openid, data.data.unionId);
				});
		},*/

		// 绑定手机号
		appletsBindMobile(loginSource) {
			if (!this.phoneNumber) {
				this.$api.msg('请输入手机号');
				return;
			}
			if (!loginSource) {
				if (!this.smsCode) {
					this.$api.msg('请输入验证码');
					return;
				}
			}

			if (this.xyvalue.length == 0) {
				this.$api.msg('请先勾选同意协议');
				return false;
			}

			// 判断是否已经绑定过了,绑定过的直接验证下客户状态，没问题就登陆了
			this.checkBindMiniProgram(this.$common.getOpenid(), this.$common.getUnionId(), loginSource);

		},
		checkBindMiniProgram(openid, unionid, loginSource) { // 判断是否已绑定  checkBindMiniProgram
			this.$u.api
				.checkBindMiniProgram({
					openId: openid || '',
					unionId: unionid || '',
					source: this.$common.source()
				})
				.then(async data => {
					if (data.data.token) { // 已经绑定过直接跳转到首页
						const token = data.data.token;
						uni.setStorageSync('token', token);
						uni.setStorageSync('expireTime', data.data.expireTime);
						// 更新登录状态
						this.$store.commit('commit_hasLogin', true);
						// 添加分销上下级关系
						await this.relationshipBusinessman();
						// 验证客户审核状态
						await this.getCustomerInfo(data.data.token, data.data.expireTime);
					} else { // 没授权过的跳转到完善资料页面
						const params = {
							mobile: this.phoneNumber,
							smsCode: this.smsCode,
							openId: this.$common.getOpenid(),
							unionId: this.$common.getUnionId(),
							salesManId: this.staffId || '',
							avatar: this.$common.getAvator() ||
								'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
							name: this.$common.getName() || '网友',
							source: loginSource || 'sms',
							type: this.$common.source(),
							shopId: 0
						};
						this.$u.api.appletsBindMobile(params).then(data => {
							this.$api.msg('登陆成功');
							uni.setStorageSync('token', data.data.token);
							uni.setStorageSync('expireTime', data.data.expireTime);
							// 更新登录状态
							this.$store.commit('commit_hasLogin', true);

							// 添加分销上下级关系跳转到完善资料界面
							this.relationshipBusinessmanOne();
						});
					}
				});
		},
		async relationshipBusinessman() { // 添加分销上下级关系 source: 1:首次点击链接 2:首次下单 3:首次付款'
			if (!this.$store.state.businessmanId) {
				return;
			}
			this.$u.api
				.relationshipBusinessman({
					businessmanId: this.$store.state.businessmanId,
					source: 1
				})
				.then(res => {
					console.log('上下:', res);
				});
		},
		getCustomerInfo(token) { // 客户审核状态校验
			this.$u.api.getCustomerInfo().then(({
				data
			}) => {
				if (data.enableStatus === 4) {
					uni.clearStorageSync();
					uni.showModal({
						title: '账号已被禁用，您可以',
						content: '联系电话：' + (data.enterpriseMobile || ''),
						confirmText: '联系客服',
						cancelText: '取消',
						success: res => {
							if (res.confirm) {
								uni.makePhoneCall({
									phoneNumber: data.enterpriseMobile
								});
							} else {
								this.goPage('/pages/binding/bindInfo', 'reLaunch');
							}
						}
					});
					return;
				}
				// if (this.$store.state.baseSet.personnelReview === 5) {
				if (data.status === 3) {
					// uni.clearStorageSync();
					// 说明资料不完善，跳转到完善资料的页面
					uni.showModal({
						title: '审核未通过，请重新修改资料',
						content: data.auditFailReason || '',
						cancelText: '联系客服',
						confirmText: '修改资料',
						success: res => {
							if (res.confirm) {
								this.goPage('/pagesT/user/editUserInfo?token=' + token);
							} else if (res.cancel) {
								uni.makePhoneCall({
									phoneNumber: data.enterpriseMobile
								});
							}
						}
					});
				} else if (data.status === 1) {
					// uni.clearStorageSync();
					uni.showModal({
						title: '账号正在审核中，您可以',
						content: '联系电话：' + (data.enterpriseMobile || ''),
						confirmText: '先去逛逛',
						cancelText: '联系客服',
						success: res => {
							if (res.confirm) {
								this.goPage('/pages/index/index', 'switchTab');
							} else {
								uni.makePhoneCall({
									phoneNumber: data.enterpriseMobile
								});
							}
						}
					});
				} else {
					this.goPage(`/pages/index/index`, 'switchTab');
				}
			});
		},
		relationshipBusinessmanOne() { // 添加分销上下级关系 source: 1:首次点击链接 2:首次下单 3:首次付款'
			if (!this.businessmanId) {
				this.goPage('/pagesT/user/editUserInfo');
				/*
				// 是否立即去完善资料
				if (this.baseSet.finishDataGo) {
					this.goPage('/pagesT/user/editUserInfo');
				} else {
					this.goPage(`/pages/index/index`, 'switchTab');
				}*/
				return;
			}
			this.$u.api
				.relationshipBusinessman({
					businessmanId: this.businessmanId,
					source: 1
				})
				.then(data => {
					console.log('上下级关系绑定成功:', data.data);
					this.goPage('/pagesT/user/editUserInfo');
					/*		
					// 是否立即去完善资料
					if (this.baseSet.finishDataGo) {
						this.goPage('/pagesT/user/editUserInfo');
					} else {
						this.goPage(`/pages/index/index`, 'switchTab');
					}*/
				});
		},
		getYzm() { // 验证码
			const re = /^1[3456789]\d{9}$/;
			if (!re.test(this.phoneNumber)) {
				this.$api.msg('手机号格式不正确');
				return;
			}

			this.$u.api
				.sendMobileCode({
					mobile: this.phoneNumber,
					source: 6
				})
				.then(res => {
					this.$api.msg('发送成功');
					// 发送验证码
					this.is_dis_yzm = !this.is_dis_yzm;
					const secondNumIn = setInterval(() => {
						this.num--;
						if (this.num === 0) {
							// 清除定时器
							clearInterval(secondNumIn);
							this.is_dis_yzm = false;
							this.num = 60;
						}
					}, 1000);
				});
		}
	}
};
</script>
<style>
page {
	background-color: #ffffff;
}
</style>
<style lang="scss" scoped>
.input-pl {
	color: #b8c0c8;
	font-size: 28rpx;
}

.box {
	.close-view {
		position: fixed;
		left: 0;
		padding-left: 30upx;
		width: 100%;
		top: 70upx;
		z-index: 99;

		.ibonguanbi1 {
			font-size: 30upx;
		}
	}

	.top-bg {
		width: 450rpx;
		height: 450rpx;
		background: linear-gradient(315deg, #FB5904 6%, #FF7A33 49%, #FF9966 88%);
		opacity: 0.08;
		filter: blur(60px);
		position: fixed;
		top: 20rpx;
		left: 0;
		z-index: 0;
	}

	.welcome-title {
		position: fixed;
		top: 162rpx;
		left: 56rpx;
		font-weight: bold;
		z-index: 1;
		line-height: 80rpx;
		font-size: 48rpx;
		font-family: PingFang SC, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen;
		color: #333333;

		view:first-child {
			color: #666666;
			font-size: 36rpx;
			margin-bottom: 10rpx;
		}

		view:last-child {
			background: linear-gradient(to right, #FB5904, #FF7A33);
			-webkit-background-clip: text;
			color: transparent;
		}
	}

	.logo-img {
		position: fixed;
		top: 150rpx;
		right: 56rpx;

		image {
			width: 130rpx;
			border-radius: 16rpx;
			height: 130rpx;
			display: block;
			box-shadow: 0px 6rpx 20rpx rgba(251, 89, 4, 0.15);
		}
	}

	.login-bg {
		position: fixed;
		top: 370rpx;
		left: 0;
		width: 100%;

		.login-container {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 0 30rpx;
		}

		.login-image {
			width: 380rpx;
			height: 380rpx;
			display: block;
			margin: 0 auto;
		}

		.login-btn-view {
			width: 638rpx;
			margin: 60rpx auto;

			.wx-Btn {
				margin-top: 20rpx;
				width: 638rpx;
				height: 96rpx;
				background: #FB5904;
				border-radius: 8rpx;
				line-height: 96rpx;
				text-align: center;
				font-weight: 500;
				color: #ffffff;
				font-size: 32rpx;
				box-shadow: 0 8rpx 16rpx rgba(251, 89, 4, 0.2);
				transition: all 0.3s ease;

				.btn-text {
					display: inline-block;
					position: relative;
				}

				&:active {
					transform: translateY(2rpx);
					box-shadow: 0 4rpx 8rpx rgba(251, 89, 4, 0.2);
				}
			}

			.yzm-Btn {
				margin-top: 40rpx;
				text-align: center;
				width: 638rpx;
				height: 80rpx;
				line-height: 80rpx;
				border-radius: 8rpx;
				border: 1px solid #cad0d7;
				color: #2d405e;
				font-size: 26rpx;

				.ibonshouji1 {
					font-size: 26rpx;
					margin-right: 14rpx;
				}
			}
		}

		.tab-ul {
			display: flex;
			padding: 56rpx;

			.tab-li {
				width: 328rpx;
				height: 88rpx;
				line-height: 88rpx;
				border-radius: 16rpx;
				color: #fa6400;
				text-align: center;
				background: linear-gradient(-62deg, transparent 32rpx, rgba(250, 100, 0, 0.08) 0) top right;
				background-size: 100% 100%;
				background-repeat: no-repeat;
				margin-right: 40rpx;
			}

			.tab-on {
				width: 328rpx;
				height: 88rpx;
				line-height: 88rpx;
				border-radius: 16rpx;
				text-align: center;
				color: #ffffff;
				font-weight: 500;
				background: linear-gradient(117deg, transparent 32rpx, #fa6400 0) top left;
				background-size: 100% 100%;
				background-repeat: no-repeat;
				margin-left: -25px;
			}
		}

		.input-ul {
			.input-li {
				color: #2d405e;
				width: 638rpx;
				margin: 40rpx auto;
				height: 80rpx;
				background: #f5f5f6;
				border-radius: 4rpx;
				position: relative;
				padding-left: 88rpx;

				.ibonfont {
					position: absolute;
					font-size: 40rpx;
					top: 50%;
					transform: translateY(-50%);
					left: 24rpx;
				}

				input {
					color: #2d405e;
					height: 80rpx;
					line-height: 80rpx;
					width: 400rpx;
				}

				.yzm-view {
					position: absolute;
					top: 50%;
					transform: translateY(-50%);
					right: 32rpx;
					color: #fa6400;
				}
			}
		}

		.login-btn {
			margin: 56rpx auto 170rpx;
			width: 638rpx;
			height: 89rpx;
			background: #fa6400;
			border-radius: 11rpx;
			line-height: 89rpx;
			text-align: center;
			font-weight: 500;
			color: #ffffff;
		}

		.divider-text {
			margin: 0 27rpx;
		}

		.wx-change-btn {
			color: #2d405e;
			margin: 50rpx auto 0;
			width: 638rpx;
			font-size: 26rpx;
			height: 80rpx;
			border-radius: 11rpx;
			line-height: 80rpx;
			text-align: center;
			border: 1px solid #cad0d7;

			.wxicon {
				vertical-align: middle;
				margin-right: 10rpx;
			}
		}
	}

	.bottom-xieyi {
		position: fixed;
		bottom: 60rpx;
		left: 0;
		z-index: 1;
		line-height: 40rpx;
		font-size: 26rpx;
		font-family: PingFang SC, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen;
		text-align: center;
		width: 100%;
		color: #666666;

		checkbox-group {
			margin-bottom: 10rpx;
		}
	}

	.bottom-xieyi label {
		display: flex;
		justify-content: center;
		align-items: center;
		flex-wrap: wrap;
	}

	.bottom-xieyi label view {
		display: inline-block;
		color: #FB5904;
		padding: 0 4rpx;
	}

}
</style>